package com.cq.hd.merchant.biz;

import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.OrderSettleBillTradeTypeEnum;
import com.cq.hd.common.enums.biz.SettleStateEnum;
import com.cq.hd.common.enums.biz.SubOrderStateEnum;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.merchant.dto.CoreDataStatisticsDto;
import com.cq.hd.merchant.dto.CoreDataTrendStatisticsDto;
import com.cq.hd.merchant.vo.CoreDataStatisticsVo;
import com.cq.hd.merchant.vo.CoreDataTrendStatisticsVo;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.TbOrderSettleBillApi;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.dto.OrderSettleBillDto;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.order.api.vo.OrderSettleBillVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class StatisticsBiz {

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private TbOrderSettleBillApi orderSettleBillApi;

    public CoreDataStatisticsVo getCoreData(CoreDataStatisticsDto allDataStatisticsDto) {
        // 日期类型：1-今日，2-本周，3-本月，4-自定义
        Integer dateType = allDataStatisticsDto.getDateType();
        if (dateType == null) {
            Throw.isBusinessException("请选择查询日期类型");
        }

        LocalDate nowLocalDate = LocalDate.now();
        if (dateType == 1) {
            String nowDateStr = LocalDateUtil.toLocalDateToString(nowLocalDate, Constant.YYYY_MM_DD);

            allDataStatisticsDto.setStartTime(nowDateStr + " 00:00:00");
            allDataStatisticsDto.setEndTime(nowDateStr + " 23:59:59");
        } else if (dateType == 2) {
            // 本周开始日期
            LocalDate monday = nowLocalDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            // 本周结束日期
            LocalDate sunday = nowLocalDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

            String mondayStartStr = LocalDateUtil.toLocalDateToString(monday, Constant.YYYY_MM_DD);
            String sundayEndStr = LocalDateUtil.toLocalDateToString(sunday, Constant.YYYY_MM_DD);

            allDataStatisticsDto.setStartTime(mondayStartStr + " 00:00:00");
            allDataStatisticsDto.setEndTime(sundayEndStr + " 23:59:59");
        } else if (dateType == 3) {
            // 本月1号
            LocalDate firstDayOfMonth = nowLocalDate.with(TemporalAdjusters.firstDayOfMonth());
            // 本月最后一天
            LocalDate lastDayOfMonth = nowLocalDate.with(TemporalAdjusters.lastDayOfMonth());

            String firstDayOfMonthStartStr = LocalDateUtil.toLocalDateToString(firstDayOfMonth, Constant.YYYY_MM_DD);
            String lastDayOfMonthEndStr = LocalDateUtil.toLocalDateToString(lastDayOfMonth, Constant.YYYY_MM_DD);

            allDataStatisticsDto.setStartTime(firstDayOfMonthStartStr + " 00:00:00");
            allDataStatisticsDto.setEndTime(lastDayOfMonthEndStr + " 23:59:59");
        } else if (dateType == 4) {
            String startTime = allDataStatisticsDto.getStartTime();
            String endTime = allDataStatisticsDto.getEndTime();
            if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
                Throw.isBusinessException("请选择查询日期");
            }

            LocalDate startLocalDate = null;
            try {
                startLocalDate = LocalDateUtil.toLocalDate(startTime, Constant.YYYY_MM_DD);
            } catch (Exception e) {
                Throw.isBusinessException("查询开始日期格式错误");
            }

            LocalDate endLocalDate = null;
            try {
                endLocalDate = LocalDateUtil.toLocalDate(endTime, Constant.YYYY_MM_DD);
            } catch (Exception e) {
                Throw.isBusinessException("查询结束日期格式错误");
            }

            // 自定义日期最长不超过3个月
            long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate);
            if (days > 90) {
                Throw.isBusinessException("自定义日期最长不超过90天");
            }

            allDataStatisticsDto.setStartTime(startTime + " 00:00:00");
            allDataStatisticsDto.setEndTime(endTime + " 23:59:59");
        }

        // 总订单金额
        BigDecimal totalOrderAmt = BigDecimal.ZERO;
        // 总订单数
        int totalOrderNum = 0;
        // 总下单人数
        int totalOrderUserNum = 0;
        // 总补贴金额=核销+结算的补贴金额
        BigDecimal totalSubsidyAmt = BigDecimal.ZERO;
        // 总收入=结算的补贴+本金
        BigDecimal totalAmt = BigDecimal.ZERO;

        // 根据日期时间查询已核销的订单项数据，获取总订单金额，总订单数，总下单人数，总补贴金额，总收入
        OrderItemDto orderItemDto = new OrderItemDto();
        orderItemDto.setMerchantId(allDataStatisticsDto.getMerchantId());
        orderItemDto.setStartVerifyTime(allDataStatisticsDto.getStartTime());
        orderItemDto.setEndVerifyTime(allDataStatisticsDto.getEndTime());

        // 2已核销 5已结算
        List<Integer> subOrderStates = new ArrayList<>();
        subOrderStates.add(SubOrderStateEnum.VERIFIED.getValue());
        subOrderStates.add(SubOrderStateEnum.SETTLED.getValue());
        orderItemDto.setSubOrderStates(subOrderStates);
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));

        List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
        if (!CollectionUtils.isEmpty(orderItemVos)) {
            // 成功下单的订单项列表
            List<OrderItemVo> successOrderItems = new ArrayList<>();

            for (OrderItemVo orderItemVo : orderItemVos) {
                // 商户订单本金(按比例分配的用户支付的订单款)
                BigDecimal merchantAmt = orderItemVo.getMerchantAmt();
                // 商户订单补贴(该订单商场补贴的金额)
                BigDecimal merchantSubsidyAmt = orderItemVo.getMerchantSubsidyAmt();

                // 累加分销订单金额
                totalOrderAmt = totalOrderAmt.add(merchantAmt);
                // 总补贴金额=核销+结算的补贴金额
                totalSubsidyAmt = totalSubsidyAmt.add(merchantSubsidyAmt);

                successOrderItems.add(orderItemVo);
            }

            if (!CollectionUtils.isEmpty(successOrderItems)) {
                // 总订单数
                totalOrderNum = successOrderItems.size();
                // 总下单人数
                totalOrderUserNum = successOrderItems.stream().map(OrderItemVo::getUserId).collect(Collectors.toSet()).size();
            }
        }

        OrderSettleBillDto orderSettleBillDto = new OrderSettleBillDto();
        orderSettleBillDto.setMerchantId(allDataStatisticsDto.getMerchantId());
        orderSettleBillDto.setStartTradeTime(allDataStatisticsDto.getStartTime());
        orderSettleBillDto.setEndTradeTime(allDataStatisticsDto.getEndTime());
        orderSettleBillDto.setTradeTypes(Arrays.asList(OrderSettleBillTradeTypeEnum.MERCHANT_AMT.getValue(), OrderSettleBillTradeTypeEnum.SUBSIDY_AMT.getValue()));
        List<OrderSettleBillVo> orderSettleBillVos = orderSettleBillApi.listByDto(orderSettleBillDto).unpack();
        if (!CollectionUtils.isEmpty(orderSettleBillVos)) {
            for (OrderSettleBillVo orderSettleBillVo : orderSettleBillVos) {
                BigDecimal tradeAmt = orderSettleBillVo.getTradeAmt();
                totalAmt = totalAmt.add(tradeAmt);
            }
        }

        CoreDataStatisticsVo coreDataStatisticsVo = new CoreDataStatisticsVo();
        coreDataStatisticsVo.setTotalOrderAmt(totalOrderAmt);
        coreDataStatisticsVo.setTotalOrderNum(totalOrderNum);
        coreDataStatisticsVo.setTotalOrderUserNum(totalOrderUserNum);
        coreDataStatisticsVo.setTotalSubsidyAmt(totalSubsidyAmt);
        coreDataStatisticsVo.setTotalAmt(totalAmt);

        return coreDataStatisticsVo;
    }

    public List<CoreDataTrendStatisticsVo> getCoreDataTrend(CoreDataTrendStatisticsDto allDataTrendStatisticsDto) {
        // 类型：1-总订单金额，2-总订单数，3-总下单人数，4-已结算补贴金额，5-总收入
        Integer type = allDataTrendStatisticsDto.getType();
        if (type == null) {
            Throw.isBusinessException("请选择查询类型");
        }

        // 日期类型：1-今日，2-本周，3-本月，4-自定义
        Integer dateType = allDataTrendStatisticsDto.getDateType();
        if (dateType == null) {
            Throw.isBusinessException("请选择查询日期类型");
        }

        LocalDate nowLocalDate = LocalDate.now();
        if (dateType == 1) {
            String nowDateStr = LocalDateUtil.toLocalDateToString(nowLocalDate, Constant.YYYY_MM_DD);

            allDataTrendStatisticsDto.setStartTime(nowDateStr + " 00:00:00");
            allDataTrendStatisticsDto.setEndTime(nowDateStr + " 23:59:59");
        } else if (dateType == 2) {
            // 本周开始日期
            LocalDate monday = nowLocalDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            // 本周结束日期
            LocalDate sunday = nowLocalDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

            String mondayStartStr = LocalDateUtil.toLocalDateToString(monday, Constant.YYYY_MM_DD);
            String sundayEndStr = LocalDateUtil.toLocalDateToString(sunday, Constant.YYYY_MM_DD);

            allDataTrendStatisticsDto.setStartTime(mondayStartStr + " 00:00:00");
            allDataTrendStatisticsDto.setEndTime(sundayEndStr + " 23:59:59");
        } else if (dateType == 3) {
            // 本月1号
            LocalDate firstDayOfMonth = nowLocalDate.with(TemporalAdjusters.firstDayOfMonth());
            // 本月最后一天
            LocalDate lastDayOfMonth = nowLocalDate.with(TemporalAdjusters.lastDayOfMonth());

            String firstDayOfMonthStartStr = LocalDateUtil.toLocalDateToString(firstDayOfMonth, Constant.YYYY_MM_DD);
            String lastDayOfMonthEndStr = LocalDateUtil.toLocalDateToString(lastDayOfMonth, Constant.YYYY_MM_DD);

            allDataTrendStatisticsDto.setStartTime(firstDayOfMonthStartStr + " 00:00:00");
            allDataTrendStatisticsDto.setEndTime(lastDayOfMonthEndStr + " 23:59:59");
        } else if (dateType == 4) {
            String startTime = allDataTrendStatisticsDto.getStartTime();
            String endTime = allDataTrendStatisticsDto.getEndTime();
            if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
                Throw.isBusinessException("请选择查询日期");
            }

            LocalDate startLocalDate = null;
            try {
                startLocalDate = LocalDateUtil.toLocalDate(startTime, Constant.YYYY_MM_DD);
            } catch (Exception e) {
                Throw.isBusinessException("查询开始日期格式错误");
            }

            LocalDate endLocalDate = null;
            try {
                endLocalDate = LocalDateUtil.toLocalDate(endTime, Constant.YYYY_MM_DD);
            } catch (Exception e) {
                Throw.isBusinessException("查询结束日期格式错误");
            }

            // 自定义日期最长不超过3个月
            long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate);
            if (days > 90) {
                Throw.isBusinessException("自定义日期最长不超过90天");
            }

            allDataTrendStatisticsDto.setStartTime(startTime + " 00:00:00");
            allDataTrendStatisticsDto.setEndTime(endTime + " 23:59:59");
        }

        //  今日 24小时  3或4小时一条
        //  本周  7天  按天
        //  其他日期按天（只能选到天））  最大不超过3个月
        // 根据日期类型判断是根据小时分组还是日期
//        String key = dateType == 1 ? "HH" : "yyyy-MM-dd";

        // 类型：1-总订单金额，2-总订单数，3-总下单人数，4-已结算补贴金额，5-总收入
        if (type == 1) {
            // 总订单金额
            Map<String, BigDecimal> map = new HashMap<>();

            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
            orderItemDto.setStartVerifyTime(allDataTrendStatisticsDto.getStartTime());
            orderItemDto.setEndVerifyTime(allDataTrendStatisticsDto.getEndTime());

            // 2已核销 5已结算
            List<Integer> subOrderStates = new ArrayList<>();
            subOrderStates.add(SubOrderStateEnum.VERIFIED.getValue());
            subOrderStates.add(SubOrderStateEnum.SETTLED.getValue());
            orderItemDto.setSubOrderStates(subOrderStates);
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));

            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                for (OrderItemVo orderItemVo : orderItemVos) {
                    // 商户订单本金(按比例分配的用户支付的订单款)
                    BigDecimal merchantAmt = orderItemVo.getMerchantAmt();
                    // 核销时间
                    LocalDateTime verifyTime = orderItemVo.getVerifyTime();

                    String mapKey = getMapKey(dateType, verifyTime);
                    BigDecimal amt = map.get(mapKey);
                    if (amt == null) {
                        amt = BigDecimal.ZERO;
                    }

                    amt = amt.add(merchantAmt);
                    map.put(mapKey, amt);
                }
            }

            List<CoreDataTrendStatisticsVo> coreDataTrendStatisticsVos = new ArrayList<>();
            if (dateType == 1) {
                for (int i = 0; i < 24; i++) {
                    String date = i < 10 ? ("0" + i) : String.valueOf(i);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);
                }
            } else {
                LocalDate startLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                LocalDate endLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
                for (int i = 0; i < days; i++) {
                    String date = LocalDateUtil.toLocalDateToString(startLocalDate, Constant.YYYY_MM_DD);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);

                    startLocalDate = startLocalDate.plusDays(1);
                }
            }

            return coreDataTrendStatisticsVos;
        } else if (type == 2) {
            // 总订单数
            Map<String, List<OrderItemVo>> map = new HashMap<>();

            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
            orderItemDto.setStartVerifyTime(allDataTrendStatisticsDto.getStartTime());
            orderItemDto.setEndVerifyTime(allDataTrendStatisticsDto.getEndTime());
            // 2已核销 5已结算
            List<Integer> subOrderStates = new ArrayList<>();
            subOrderStates.add(SubOrderStateEnum.VERIFIED.getValue());
            subOrderStates.add(SubOrderStateEnum.SETTLED.getValue());
            orderItemDto.setSubOrderStates(subOrderStates);
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                for (OrderItemVo orderItemVo : orderItemVos) {
                    // 核销时间
                    LocalDateTime verifyTime = orderItemVo.getVerifyTime();

//                    String mapKey = LocalDateUtil.toLocalDateToString(orderTime.toLocalDate(), key);
                    String mapKey = getMapKey(dateType, verifyTime);
                    List<OrderItemVo> orderItems = map.get(mapKey);
                    if (CollectionUtils.isEmpty(orderItems)) {
                        orderItems = new ArrayList<>();
                    }
                    orderItems.add(orderItemVo);
                    map.put(mapKey, orderItems);
                }
            }

            List<CoreDataTrendStatisticsVo> coreDataTrendStatisticsVos = new ArrayList<>();
            if (dateType == 1) {
                for (int i = 0; i < 24; i++) {
                    int orderNum = 0;
                    String date = i < 10 ? ("0" + i) : String.valueOf(i);
                    List<OrderItemVo> orderItems = map.get(date);
                    if (!CollectionUtils.isEmpty(orderItems)) {
                        orderNum = orderItems.size();
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(String.valueOf(orderNum));
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);
                }
            } else {
                LocalDate startLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                LocalDate endLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
                for (int i = 0; i < days; i++) {
                    int orderNum = 0;
                    String date = LocalDateUtil.toLocalDateToString(startLocalDate, Constant.YYYY_MM_DD);
                    List<OrderItemVo> orderItems = map.get(date);
                    if (!CollectionUtils.isEmpty(orderItems)) {
                        orderNum = orderItems.size();
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(String.valueOf(orderNum));
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);

                    startLocalDate = startLocalDate.plusDays(1);
                }
            }

            return coreDataTrendStatisticsVos;
        } else if (type == 3) {
            // 总下单人数
            Map<String, List<OrderItemVo>> map = new HashMap<>();

            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
            orderItemDto.setStartVerifyTime(allDataTrendStatisticsDto.getStartTime());
            orderItemDto.setEndVerifyTime(allDataTrendStatisticsDto.getEndTime());
            // 2已核销 5已结算
            List<Integer> subOrderStates = new ArrayList<>();
            subOrderStates.add(SubOrderStateEnum.VERIFIED.getValue());
            subOrderStates.add(SubOrderStateEnum.SETTLED.getValue());
            orderItemDto.setSubOrderStates(subOrderStates);
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                for (OrderItemVo orderItemVo : orderItemVos) {
                    // 核销时间
                    LocalDateTime verifyTime = orderItemVo.getVerifyTime();
//                    String mapKey = LocalDateUtil.toLocalDateToString(orderTime.toLocalDate(), key);
                    String mapKey = getMapKey(dateType, verifyTime);
                    List<OrderItemVo> orderItems = map.get(mapKey);
                    if (CollectionUtils.isEmpty(orderItems)) {
                        orderItems = new ArrayList<>();
                    }
                    orderItems.add(orderItemVo);
                    map.put(mapKey, orderItems);
                }
            }

            List<CoreDataTrendStatisticsVo> coreDataTrendStatisticsVos = new ArrayList<>();
            if (dateType == 1) {
                for (int i = 0; i < 24; i++) {
                    int orderUserNum = 0;
                    String date = i < 10 ? ("0" + i) : String.valueOf(i);
                    List<OrderItemVo> orderItems = map.get(date);
                    if (!CollectionUtils.isEmpty(orderItems)) {
                        orderUserNum = orderItems.stream().map(OrderItemVo::getUserId).collect(Collectors.toSet()).size();
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(String.valueOf(orderUserNum));
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);
                }
            } else {
                LocalDate startLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                LocalDate endLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
                for (int i = 0; i < days; i++) {
                    int orderUserNum = 0;
                    String date = LocalDateUtil.toLocalDateToString(startLocalDate, Constant.YYYY_MM_DD);
                    List<OrderItemVo> orderItems = map.get(date);
                    if (!CollectionUtils.isEmpty(orderItems)) {
                        orderUserNum = orderItems.stream().map(OrderItemVo::getUserId).collect(Collectors.toSet()).size();
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(String.valueOf(orderUserNum));
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);

                    startLocalDate = startLocalDate.plusDays(1);
                }
            }

            return coreDataTrendStatisticsVos;
        } else if (type == 4) {
            // 总补贴金额=核销+结算的补贴金额
            Map<String, BigDecimal> map = new HashMap<>();

            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
            orderItemDto.setStartVerifyTime(allDataTrendStatisticsDto.getStartTime());
            orderItemDto.setEndVerifyTime(allDataTrendStatisticsDto.getEndTime());
            // 2已核销 5已结算
            List<Integer> subOrderStates = new ArrayList<>();
            subOrderStates.add(SubOrderStateEnum.VERIFIED.getValue());
            subOrderStates.add(SubOrderStateEnum.SETTLED.getValue());
            orderItemDto.setSubOrderStates(subOrderStates);
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                for (OrderItemVo orderItemVo : orderItemVos) {
                    // 商户订单补贴(该订单商场补贴的金额)
                    BigDecimal merchantSubsidyAmt = orderItemVo.getMerchantSubsidyAmt();
                    // 核销时间
                    LocalDateTime verifyTime = orderItemVo.getVerifyTime();

//                    String mapKey = LocalDateUtil.toLocalDateToString(orderTime.toLocalDate(), key);
                    String mapKey = getMapKey(dateType, verifyTime);
                    BigDecimal amt = map.get(mapKey);
                    if (amt == null) {
                        amt = BigDecimal.ZERO;
                    }
                    amt = amt.add(merchantSubsidyAmt);
                    map.put(mapKey, amt);
                }
            }


            List<CoreDataTrendStatisticsVo> coreDataTrendStatisticsVos = new ArrayList<>();
            if (dateType == 1) {
                for (int i = 0; i < 24; i++) {
                    String date = i < 10 ? ("0" + i) : String.valueOf(i);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);
                }
            } else {
                LocalDate startLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                LocalDate endLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
                for (int i = 0; i < days; i++) {
                    String date = LocalDateUtil.toLocalDateToString(startLocalDate, Constant.YYYY_MM_DD);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);

                    startLocalDate = startLocalDate.plusDays(1);
                }
            }

            return coreDataTrendStatisticsVos;
        } else if (type == 5) {
            // 总收入=结算的补贴+本金

            Map<String, BigDecimal> map = new HashMap<>();

            OrderSettleBillDto orderSettleBillDto = new OrderSettleBillDto();
            orderSettleBillDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
            orderSettleBillDto.setStartTradeTime(allDataTrendStatisticsDto.getStartTime());
            orderSettleBillDto.setEndTradeTime(allDataTrendStatisticsDto.getEndTime());
            orderSettleBillDto.setTradeTypes(Arrays.asList(OrderSettleBillTradeTypeEnum.MERCHANT_AMT.getValue(), OrderSettleBillTradeTypeEnum.SUBSIDY_AMT.getValue()));
            List<OrderSettleBillVo> orderSettleBillVos = orderSettleBillApi.listByDto(orderSettleBillDto).unpack();
            if (!CollectionUtils.isEmpty(orderSettleBillVos)) {
                for (OrderSettleBillVo orderSettleBillVo : orderSettleBillVos) {
                    LocalDateTime tradeTime = orderSettleBillVo.getTradeTime();
                    BigDecimal tradeAmt = orderSettleBillVo.getTradeAmt();

                    String mapKey = getMapKey(dateType, tradeTime);
                    BigDecimal amt = map.get(mapKey);
                    if (amt == null) {
                        amt = BigDecimal.ZERO;
                    }
                    amt = amt.add(tradeAmt);
                    map.put(mapKey, amt);
                }
            }



//            OrderItemDto orderItemDto = new OrderItemDto();
//            orderItemDto.setMerchantId(allDataTrendStatisticsDto.getMerchantId());
//            orderItemDto.setStartVerifyTime(allDataTrendStatisticsDto.getStartTime());
//            orderItemDto.setEndVerifyTime(allDataTrendStatisticsDto.getEndTime());
//            orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
//            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
//            if (!CollectionUtils.isEmpty(orderItemVos)) {
//                for (OrderItemVo orderItemVo : orderItemVos) {
//                    if (SettleStateEnum.YES.getValue().equals(orderItemVo.getSettleState())) {
//                        // 商户订单本金(按比例分配的用户支付的订单款)
//                        BigDecimal merchantAmt = orderItemVo.getMerchantAmt();
//                        // 商户订单补贴(该订单商场补贴的金额)
//                        BigDecimal merchantSubsidyAmt = orderItemVo.getMerchantSubsidyAmt();
//                        // 核销时间
//                        LocalDateTime verifyTime = orderItemVo.getVerifyTime();
//
////                        String mapKey = LocalDateUtil.toLocalDateToString(orderTime.toLocalDate(), key);
//                        String mapKey = getMapKey(dateType, verifyTime);
//                        BigDecimal amt = map.get(mapKey);
//                        if (amt == null) {
//                            amt = BigDecimal.ZERO;
//                        }
//                        amt = amt.add(merchantAmt).add(merchantSubsidyAmt);
//                        map.put(mapKey, amt);
//                    }
//                }
//            }


            List<CoreDataTrendStatisticsVo> coreDataTrendStatisticsVos = new ArrayList<>();
            if (dateType == 1) {
                for (int i = 0; i < 24; i++) {
                    String date = i < 10 ? ("0" + i) : String.valueOf(i);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);
                }
            } else {
                LocalDate startLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                LocalDate endLocalDate = LocalDateUtil.toLocalDateTime(allDataTrendStatisticsDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS).toLocalDate();
                long days = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
                for (int i = 0; i < days; i++) {
                    String date = LocalDateUtil.toLocalDateToString(startLocalDate, Constant.YYYY_MM_DD);
                    BigDecimal bigDecimal = map.get(date);
                    if (bigDecimal == null) {
                        bigDecimal = BigDecimal.ZERO;
                    }

                    CoreDataTrendStatisticsVo coreDataTrendStatisticsVo = new CoreDataTrendStatisticsVo();
                    coreDataTrendStatisticsVo.setDate(date);
                    coreDataTrendStatisticsVo.setValue(bigDecimal.toString());
                    coreDataTrendStatisticsVos.add(coreDataTrendStatisticsVo);

                    startLocalDate = startLocalDate.plusDays(1);
                }
            }

            return coreDataTrendStatisticsVos;
        }

        return null;
    }

    private String getMapKey(Integer dateType, LocalDateTime localDateTime) {
        String mapKey;
        if (dateType == 1) {
            int hour = localDateTime.getHour();
            mapKey = hour > 9 ? String.valueOf(hour) : "0" + hour;
        } else {
            mapKey = LocalDateUtil.toLocalDateToString(localDateTime.toLocalDate(), Constant.YYYY_MM_DD);
        }
        return mapKey;
    }

}
